﻿namespace $safeprojectname$
open System
open System.IO
open System.Windows
open System.Windows.Controls
open System.Windows.Markup
open System.Xml.Linq
open DaveSexton.Labs

/// Labs derived from this class may define a custom graphical user interface (GUI).
[<System.ComponentModel.Composition.PartNotDiscoverable>]
type public BaseLab(sourceFileName : string) as this =
#if SILVERLIGHT
#if WINDOWS_PHONE
    inherit PhoneLab()
    do this.InitializeComponent(sourceFileName)
#else
    inherit SilverlightLab()
    do this.InitializeComponent(sourceFileName)
#endif
#else
#if WINDOWS
    inherit WindowsLab()
    do this.InitializeComponent(sourceFileName)
#else
    inherit Lab()
#endif
#endif
    member this.InitializeComponent(sourceFileName : string) =
        let uri = new Uri("/" + Path.GetFileNameWithoutExtension(sourceFileName), UriKind.Relative)
        let removeClass = fun (xml : Stream) ->
            let doc = XDocument.Load(xml)
            let x = XNamespace.Get("http://schemas.microsoft.com/winfx/2006/xaml")
            let cls = doc.Root.Attribute(x + "Class")
            match cls with
            | null -> ignore()
            | _ -> cls.Remove()
            doc.ToString()
        #if SILVERLIGHT
        use stream = Application.GetResourceStream(uri).Stream
        let lab = XamlReader.Load(removeClass stream) :?> UserControl
        #else
        #if WINDOWS
        use stream = Application.GetResourceStream(uri).Stream
        let lab = XamlReader.Parse(removeClass stream) :?> UserControl
        #else
        let lab = null : UserControl
        #endif
        #endif
        match lab with
        | null -> ignore()
        | _ -> 
            let content = lab.Content
            lab.Content <- null
            this.Content <- content

    member this.FindName<'T when 'T :> DependencyObject>(name : string) : 'T =
        LogicalTreeHelper.FindLogicalNode(this, name) :?> 'T